import fse from "fs-extra";
import chalk from "chalk";
import XLSX from "xlsx";

async function makeDir(path) {
  return await fse.ensureDir(path);
}

async function readDir(path) {
  let paths = await fse.readdir(path);
  return paths;
}

function writeFile(path, data) {
  return fse.writeFileSync(path, data);
}

const readFile = async (fileName, options: Options) => {
  const workbook = XLSX.readFile(fileName);
  const sheetNames = Object.keys(workbook.Sheets || {});
  const sheetObj = workbook.Sheets[sheetNames[0]];
  const jsons = XLSX.utils.sheet_to_json(sheetObj);
  const newCsv = [];
  // 处理数据生成文件
  let { namespaceKey, getPageName, langs, outPath, suffix } = options;
  let result = {};
  (jsons || []).forEach((i: any, index) => {
    let namespace = namespaceKey || "namespace";
    let pageName = getPageName(i[namespace]);
    if (pageName) {
      newCsv.push(i);
      (langs || ["en"]).forEach(l => {
        let pathKey = `${pageName}/${l}.${suffix || "json"}`;
        result[pathKey] = result[pathKey] || {};
        i.key && (result[pathKey][i.key || null] = i[l] || "");
      });
    }
  });
  // 提取表头
  const headers = XLSX.utils.sheet_to_json(sheetObj, { header: 1 })[0];
  const csvData = [];
  csvData.push(headers);
  // 提取数据行
  newCsv.forEach(row => {
    const rowData = headers.map(header => row[header]);
    csvData.push(rowData);
  });
  const csvOutput = XLSX.utils.sheet_to_csv(XLSX.utils.aoa_to_sheet(csvData));
  // 添加 BOM 以确保中文字符正确显示
  const bom = "\uFEFF";
  const csvWithBom = bom + csvOutput;
  // 写入 CSV 文件，确保使用 UTF-8 编码
  writeFile("locale.csv", csvWithBom);
  console.log("CSV 文件已成功写入");
  // 生成文件
  (Object.keys(result) || []).forEach(async k => {
    let data = JSON.stringify(result[k], null, 2);
    await makeDir(`${outPath}/${k.split("/")[0]}`);
    writeFile(`${outPath}/${k}`, data);
  });
};

// const fileRegex = /\.(csv|xls|xlsx)$/
const fileRegex = /\.(csv)$/;

type Options = {
  path: string;
  outPath: string;
  suffix?: string;
  namespaceKey?: string;
  getPageName: Function;
  langs: string[];
};

let cacheOpt: Options;

export default function excelPlugin(data: Options) {
  return {
    name: "vite-plugin-excel",
    enforce: "pre",
    async buildStart(options) {
      cacheOpt = data;
      // 获取 excel 文件
      let paths = (await readDir(data.path)).filter(p => fileRegex.test(p));
      if (!paths.length) {
        console.log(chalk.yellow(`no excel file in ${data.path}`));
        return;
      }
      // 处理文件生成
      paths.forEach(p => {
        readFile(`${data.path}/${p}`, cacheOpt);
      });
    },
    handleHotUpdate(ctx) {
      if (fileRegex.test(ctx.file)) {
        readFile(ctx.file, cacheOpt);
        ctx.server.ws.send({
          type: "full-reload",
          path: "*",
        });
      }
      return ctx.modules;
    },
  };
}
